//监听文件自动生成路由
const fs = require('fs');
const path = require('path');

const config = {
	"custom": {
		"^u--(.*)": "@/uni_modules/uview-plus/components/u-$1/u-$1.vue",
		"^up-(.*)": "@/uni_modules/uview-plus/components/u-$1/u-$1.vue",
		"^u-([^-].*)": "@/uni_modules/uview-plus/components/u-$1/u-$1.vue"
	},
	"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "新君涛验车",
		"navigationBarBackgroundColor": "#ffffff",
		"backgroundColor": "#ffffff",
	},
	"uniIdRouter": {}
};

const api_public = './public/files/applet';

let is_run;
fs.watch('./pages', {recursive: true}, (eventType, filename) => {
	if(!is_run){
		is_run = setTimeout(()=>{
			up_pages()
		},100)
	}else{
		clearTimeout(is_run);
		is_run = setTimeout(()=>{
			up_pages()
		},100)
	}
});

let pages_str = '';

up_pages();

function up_pages(){
	let pages = [];
	let tabBar_list = [];
	let subPackages = {};

	let pages_dir = path.resolve(__dirname, './pages');
	
	let dirs = (dirPath)=>{
		const files = fs.readdirSync(dirPath);

		files.forEach(file => {
			const fullPath = path.join(dirPath, file);
			const stats = fs.statSync(fullPath);
			if (stats.isDirectory()) {
				dirs(fullPath);
			} else {
				let extname = path.extname(fullPath).toLowerCase();
				if(extname == '.png' || extname == '.jpg' || extname == '.jpeg' || extname == '.gif'){
					copyFile(fullPath,api_public + fullPath.substr(5))
				}else if(extname == '.vue' && /^[\da-zA-Z_\-\/\\]+$/.test(fullPath.substr(0,fullPath.length-4))){
					let page_path = fullPath.replace(pages_dir,'').replace(/\\/g,'/').replace('.vue','');
					
					let file_data = fs.readFileSync(fullPath, 'utf8');
					let file_data_arr = file_data.split('*/');

					if(file_data_arr.length){
						let conf = file_data_arr[0].trim()
						if(conf.indexOf('/**') === 0){
							conf = conf.replace('/**','')
							let page = eval('(' + conf + ')');
							
							page.path = page_path;

							if(typeof page.tabBar == 'object'){
								let tabBar = page.tabBar;
								delete page.tabBar;

								tabBar.pagePath = page_path;
								tabBar_list.push(tabBar);
							}

							let paths = page_path.split('/');
							if(paths.length == 3){
								pages.push(page);
							}else if(paths.length > 3){
								let root = paths.splice(0,2).join('/');

								if(!subPackages[root]){
									subPackages[root] = {
										root: root,
										pages: []
									}
								}

								page.path = paths.join('/');

								subPackages[root].pages.push(page);

							}
						}
					}
				}
			}
		});
	}
	
	dirs('./pages');

	tabBar_list.sort((a,b)=>{
		return a.index - b.index;
	})

	if(tabBar_list.length){
		config.tabBar = {
			"color": "#999999",
			"selectedColor": "#348B8A",
			"borderStyle": "black",
			"backgroundColor": "#ffffff",
			"fontSize": "16px",
			"custom": true,
			"list": tabBar_list
		}
	}

	let index = pages.findIndex(v=>v.path == (tabBar_list.length?tabBar_list[0].pagePath:'pages/index/index'));
	if(index > 0){
		pages = pages.splice(index,1).concat(pages);
	}

	config.pages = pages;

	if(Object.keys(subPackages).length){
		config.subPackages = Object.values(subPackages);
	}

	//写入文件
	let save_str = JSON.stringify(config,'\t','\t','\t');
	if(pages_str != save_str){
		fs.writeFileSync('./pages.json', JSON.stringify(config,'\t','\t','\t'), 'utf8');
		pages_str = save_str;
		console.log('pages.json  文件已生成')
	}
}

function copyFile(source, destination) {
	const destinationDir = path.dirname(destination);
	//判断destinationDir是否存在
	if(!fs.existsSync(destinationDir)){
		fs.mkdirSync(destinationDir, { recursive: true })
	}

	//判断文件是否存在
	if(!fs.existsSync(destination)){
		//复制文件
		fs.copyFile(source, destination, (err) => {
			if (err) {
				console.error(`Error copying ${source} to ${destination}: ${err}`);
			} else {
				console.log(source + '  文件已生成');
			}
		});
	}
}